import {Component, OnInit, ViewChild} from '@angular/core';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../../../config/api';
import {ActivatedRoute} from '@angular/router';
import {HttpService} from '../../../../lib/service/http.service';
import {AdOssUploadService} from '../../../../lib/service/ad-oss-upload.service';
import {ModalDirective} from 'ngx-bootstrap';
import {EditTemplate, AddShowcase, EditShowcase} from '../../template'

@Component({
  selector: 'app-add-template',
  templateUrl: 'editTemp.component.html',
  styleUrls: ['editTemp.component.scss'],
  providers: [HttpService]
})
export class EditTemplateComponent implements OnInit {

  template_id: number;
  addShowcase = new AddShowcase;
  editShowcase = new EditShowcase;
  editTemplate = new EditTemplate;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  typeList: any = ''; // 模板类型列表
  hasUploadShowcaseImg = true;  // 是否已经上传展位图
  tempImgChanges = false;  // 模板图片是够修改
  showcaseImgChanged = false;  // 编辑模块中的图片是否已改变

  type: string;
  message: string;
  isShow = false;
  img_file: any;
  img_name: string;  // 模板图片
  img_url: string;
  showcaseImg_file: any;
  showcaseImg_name: string;  // 展示图片名称
  showcaseImg_url: string;  // 展示图片url
  showcaseList = ''; // 展位列表
  operateId: number;

  @ViewChild('addModuleModal') public addModuleModal: ModalDirective;
  @ViewChild('editModuleModal') public editModuleModal: ModalDirective;
  @ViewChild('deleteModal') public deleteModal: ModalDirective;

  constructor(private httpService: HttpService,
              private adOssUploadService: AdOssUploadService,
              private route: ActivatedRoute) {
  }

  ngOnInit() {
    this.getTemplateDetail();
    this.getTemplateTypeList();
    this.getShowcaseList();
  }

  // 获取模板详情并赋值
  getTemplateDetail() {
    this.template_id = +this.route.snapshot.params['id'];
    const url = `${adSystemApiUrl}/v1/admin/template_applet/${this.template_id}/info`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.editTemplate = res.data;

        if (!!this.editTemplate.screenshot) {
          this.img_url = this.aliyunOssOutputUrl + '/' + this.editTemplate.screenshot;
        }
      }
    );
  }

  // 获取模板类型列表
  getTemplateTypeList() {
    const url = `${adSystemApiUrl}/v1/admin/template_category/list?page=1&pageSize=200`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.typeList = res.data.data;
        this.editTemplate.category_id = this.typeList[0].id;
      }
    );
  }

  // 获取展位列表
  getShowcaseList() {
    const url = `${adSystemApiUrl}/v1/admin/show_case/list?template_id=${this.template_id}&order={"sort":"asc"}&page=1&pageSize=200`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.showcaseList = res.data.data;
      }
    );
  }

  // 模板上传图片
  uploadImg($event: any, imgName: string) {
    const file = $event.path[0].files[0];
    const myReader = new FileReader();
    const self = this;
    const suffix = file.name.replace(/.+\./, '').toLowerCase();
    if (imgName === 'temp') {
      this.img_file = file;
      this.img_name = imgName + '.' + suffix;
      this.tempImgChanges = true;
      myReader.readAsDataURL(file);
      myReader.onloadend = function (e) {
        self.img_url = myReader.result;
      };
    } else {
      this.showcaseImg_file = file;
      this.showcaseImg_name = imgName + '.' + suffix;
      myReader.readAsDataURL(file);
      myReader.onloadend = function (e) {
        self.showcaseImg_url = myReader.result;
      };
    }
  }

  editImg($event: any, imgName?: string) {
    this.showcaseImgChanged = true;
    const file = $event.path[0].files[0];
    const myReader = new FileReader();
    const self = this;
    const suffix = file.name.replace(/.+\./, '').toLowerCase();
    const now = new Date();
    this.showcaseImg_file = file;
    this.showcaseImg_name = now.getTime() + imgName + '.' + suffix;
    myReader.readAsDataURL(file);
    myReader.onloadend = function (e) {
      self.showcaseImg_url = myReader.result;
    };
  }

  // 提交模板
  editTemplateSubmit() {
    const url = `${adSystemApiUrl}/v1/admin/template_applet/edit_v2`;
    return this.httpService.httpPostAuth(url, this.editTemplate).subscribe(
      res => {
        if (res.code === 2000) {
          if (!!this.tempImgChanges) {
            this.adOssUploadService.getSignature('/v1/common/templateApplet/' + this.template_id + '?callback=true').subscribe(
              res1 => {
                this.adOssUploadService.fileUpload(this.img_file, res1.data, this.img_name, 'screenshot').subscribe(
                  res2 => {
                    if (res2.status === 200) {
                      this.type = 'success';
                      this.message = '保存成功';
                      this.isShow = true;
                    }
                  }
                );
              }
            );
          } else {
            this.type = 'success';
            this.message = '保存成功';
            this.isShow = true;
          }
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 添加展位
  showcaseSubmit() {
    if (!this.showcaseImg_name) {
      this.hasUploadShowcaseImg = false;
      return;
    }
    this.addShowcase.area_diagram = this.showcaseImg_name;
    this.addShowcase.template_id = this.template_id;
    const url = `${adSystemApiUrl}/v1/admin/show_case/add`;
    return this.httpService.httpPostAuth(url, this.addShowcase).subscribe(
      res => {
        if (res.code === 2000) {
          this.adOssUploadService.getSignature('/v1/common/showcase/' + res.data.id + '?callback=true').subscribe(
            res1 => {
              this.adOssUploadService.fileUpload(this.showcaseImg_file, res1.data, this.showcaseImg_name, 'area_diagram').subscribe(
                res2 => {
                  if (res2.status === 200) {
                    this.type = 'success';
                    this.message = '展位添加成功';
                    this.isShow = true;
                    this.img_file = null;
                    this.showcaseImg_name = null;
                    this.showcaseImg_url = null;
                    this.addModuleModal.hide();
                    this.getShowcaseList();
                  }
                }
              );
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 编辑展位
  editShowcaseDialog(id: number) {
    const url = `${adSystemApiUrl}/v1/admin/show_case/${id}/info`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        if (res.code === 2000) {
          this.editShowcase = res.data;
          this.showcaseImg_url = this.aliyunOssOutputUrl + '/' + res.data.area_diagram;
          this.showcaseImgChanged = false;
          this.editModuleModal.show();
        }
      }
    );
  }

  // 编辑展位后提交
  editShowcaseSubmit() {
    const url = `${adSystemApiUrl}/v1/admin/show_case/edit`;
    return this.httpService.httpPostAuth(url, this.editShowcase).subscribe(
      res => {
        if (res.code === 2000) {
          if (!!this.showcaseImgChanged) {
            this.adOssUploadService.getSignature('/v1/common/showcase/' + this.editShowcase.id + '?callback=true').subscribe(
              res1 => {
                this.adOssUploadService.fileUpload(this.showcaseImg_file, res1.data, this.showcaseImg_name, 'area_diagram').subscribe(
                  res2 => {
                    if (res2.status === 200) {
                      this.type = 'success';
                      this.message = '展位编辑成功';
                      this.isShow = true;
                      this.showcaseImg_name = null;
                      this.showcaseImg_url = null;
                      this.editModuleModal.hide();
                      this.getShowcaseList();
                    } else {
                      this.type = 'error';
                      this.message = '图片上传失败';
                      this.isShow = true;
                    }
                  }
                );
              }
            );
          } else {
            this.type = 'success';
            this.message = '展位编辑成功';
            this.isShow = true;
            this.showcaseImg_name = null;
            this.showcaseImg_url = null;
            this.editModuleModal.hide();
            this.getShowcaseList();
          }
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 删除展位
  delShowcase(id: number) {
    this.operateId = id;
    this.deleteModal.show();
  }

  // 确认删除展位
  delShowcaseSubmit() {
    const url = `${adSystemApiUrl}/v1/admin/show_case/${this.operateId}/del`;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '展位删除成功';
          this.isShow = true;
          this.deleteModal.hide();
          this.getShowcaseList();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }


}
